#include<iostream>
#include<cstring>
using namespace std;


int n, m;
const int N = 505;
int g[N][N];
int dist[N];
bool st[N];
int Dijkstra() {
    memset(dist, 0x3f, sizeof(dist));
    dist[1] = 0;
    for (int i = 1; i < n; i++) {
        int temp = -1;
        for (int j = 1; j <= n; j++) {
            if (!st[j] && (temp == -1 || dist[temp] > dist[j]))temp = j;
        }

        st[temp] = true;
        for (int j = 1; j <= n; j++) {
            dist[j] = min(dist[j], dist[temp] + g[temp][j]);
        }
    }
    return dist[n] == 0x3f3f3f3f ? -1 : dist[n];


}

int main() {
    memset(g, 0x3f, sizeof(g));
    cin >> n >> m;
    int a, b, c;
    while (m--) {
        cin >> a >> b >> c;
        g[a][b] = min(g[a][b], c);
    }
    cout << Dijkstra() << endl;
}